package com.fau.wmbj.server.controller;

import com.fau.wmbj.server.config.CurrentUser;
import com.fau.wmbj.server.entity.Company;
import com.fau.wmbj.server.entity.Role;
import com.fau.wmbj.server.entity.User;
import com.fau.wmbj.server.service.CompanyService;
import com.fau.wmbj.server.service.UserService;
import com.fau.wmbj.server.utils.Filter;
import com.fau.wmbj.server.utils.Message;
import com.fau.wmbj.server.utils.Page;
import com.fau.wmbj.server.utils.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 单位
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2024-03-18 10:11
 */
@RestController
@RequestMapping("/company")
public class CompanyController {

    @Resource
    private CompanyService companyService;
    @Resource
    private UserService userService;

    /**
     * 分页查询
     */
    @RequestMapping(value = "/getUserCountByCompany", method = RequestMethod.POST)
    @ResponseBody
    public Message getUserCountByCompany(@RequestBody Company company) {
        Long id = company.getId();
        long count = userService.count(Filter.eq("role.company.id", id));
        return Message.success(count);
    }

    /**
     * 分页查询
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ResponseBody
    public Message page(@RequestBody Pageable pageable) {
        Page<Company> page = companyService.findPage(pageable);
        return Message.success(page);
    }

    /**
     * 添加
     */
    @RequestMapping("/save")
    public Message save(@RequestBody Company company, @CurrentUser User user) {
        Map<String, Object> params = company.getParams();
        List<Integer> ids = (List<Integer>) params.get("menuIds");
        List<Long> ids2 = new ArrayList<>();
        for (Integer id : ids) {
            ids2.add(Long.valueOf(id));
        }
        companyService.save(company, ids2);
        return Message.success();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public Message update(@RequestBody Company company) {
        Map<String, Object> params = company.getParams();
        List<Integer> ids = (List<Integer>) params.get("menuIds");
        List<Long> ids2 = new ArrayList<>();
        for (Integer id : ids) {
            ids2.add(Long.valueOf(id));
        }
        companyService.update(company, ids2);
        return Message.success();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public Message delete(@RequestBody Role role) {
        Long[] ids = role.getIds();
        try {
            for (Long id : ids) {
                companyService.delete(id);
            }
        } catch (Exception e) {
            return Message.error(e.getMessage());
        }
        return Message.success();
    }

}
